<template>
  <div class="my_page_container">
    <q-splitter
      class="bg-white"
      v-model="splitterRatio"
      style="height: 550px"
    >
      <template v-slot:before>
        <div class="row q-pa-xs q-gutter-sm">
          <q-input outlined dense color="base" style="width: 120px">
            <template v-slot:append>
              <q-icon name="search" color="indigo" />
            </template>
          </q-input>
          <q-btn
            dense
            outline
            size="sm"
            color="primary"
            label="刷新"
            icon="refresh"
          />
        </div>
        <q-separator />
        <q-scroll-area
          class="my-scroll-area"
        >
          <div class="q-ma-md my-text-overflow">
            <q-tree
              icon="mdi-key"
              ref="myNavTreeRef"
              :nodes="uTreeList"
              node-key="sid"
              label-key="name"
              selected-color="primary"
              no-connectors="false"
              default-expand-all
              v-model:selected="myNavTreeSelectedItem"
              @update:selected="onNavTreeSelected"
            />
        </div>
        </q-scroll-area>
      </template>

      <template v-slot:after>
        <div class="bg-white">
          <AmyQueryItem
            search-label="属性名称"
            @make-search-condition="queryTable"
          />
        </div>
        <div class="bg-white">
          <q-scroll-area
            class="my_scroll_area_table"
          >
            <q-table
              id="my-xls"
              bordered
              flat
              separator="cell"
              :tableTitle= "tableTitle"
              :columns="columns"
              row-key="name"
              :rows="dbFilterList"
              :pagination="dbPagination"
              :rows-per-page-options="[10,20]"
              selection="multiple"
              v-model:selected="selectedItems"
            >

              <!--  插槽：表格头部左侧    -->
              <template v-slot:top-left>
                <q-input outlined dense color="base" v-model="filterText" :input-style="{ width: '150px'}">
                  <template v-slot:append>
                    <q-icon name="search" color="indigo"/>
                  </template>
                </q-input>
              </template>

              <!--  插槽：表格头部左侧    -->
              <template v-slot:top-right>
                <div class="q-gutter-sm">
                  <q-btn
                    dense
                    unelevated
                    color="secondary"
                    label="新增"
                    icon="mdi-comment-plus"
                    @click="addDlgItem"
                  />
                  <q-btn
                    dense
                    unelevated
                    color="amber"
                    label="导入"
                    icon="mdi-file-import"
                  />
                  <q-btn
                    dense
                    unelevated
                    color="pink"
                    label="导出"
                    icon="mdi-database-export"
                    @click="exportExcel"
                  />
                </div>
              </template>

              <!--  插槽：某个单元格    -->
              <template #body-cell-comId="props">
                <q-td :props="props">
                  <q-select
                    :readonly="bIsReadOnly[props.rowIndex]"
                    dense
                    outlined
                    options-dense
                    :options="hmiComponentList"
                    v-model="props.row.comId"
                    option-value="id"
                    emit-value
                    options-selected-class="teal"
                    :label="findCatalogLabel(hmiComponentList, props.row.comId)"
                    style="width: 100px"
                  />
                </q-td>
              </template>
              <template #body-cell-dataTypeId="props">
                <q-td :props="props">
                  <q-select
                    :readonly="bIsReadOnly[props.rowIndex]"
                    dense
                    outlined
                    options-dense
                    :options="propDataTypeList"
                    v-model="props.row.dataTypeId"
                    option-value="id"
                    emit-value
                    options-selected-class="teal"
                    :label="findCatalogLabel(propDataTypeList, props.row.dataTypeId)"
                    style="width: 100px"
                  />
                </q-td>
              </template>
              <template #body-cell-formTypeId="props">
                <q-td :props="props">
                  <q-select
                    :readonly="bIsReadOnly[props.rowIndex]"
                    dense
                    outlined
                    options-dense
                    :options="propFormTypeList"
                    v-model="props.row.formTypeId"
                    option-value="id"
                    emit-value
                    options-selected-class="teal"
                    :label="findCatalogLabel(propFormTypeList, props.row.formTypeId)"
                    style="width: 100px"
                  />
                </q-td>
              </template>
              <template #body-cell-label="props">
                <q-td :props="props">
                  <q-input
                    :readonly="bIsReadOnly[props.rowIndex]"
                    dense
                    outlined
                    v-model="props.row.label"
                  />
                </q-td>
              </template>
              <template #body-cell-value="props">
                <q-td :props="props">
                  <q-input
                    :readonly="bIsReadOnly[props.rowIndex]"
                    dense
                    outlined
                    v-model="props.row.value"
                  />
                </q-td>
              </template>
              <template #body-cell-sortCode="props">
                <q-td :props="props">
                  <q-input
                    :readonly="bIsReadOnly[props.rowIndex]"
                    dense
                    outlined
                    v-model="props.row.sortCode"
                  />
                </q-td>
              </template>
              <template #body-cell-operation="props">
                <q-td :props="props">
                  <q-btn
                    flat
                    round
                    dense
                    color="primary"
                    icon="edit"
                    @click="editDlgItem(props.rowIndex)">
                    <q-tooltip>编辑</q-tooltip>
                  </q-btn>
                  <q-btn
                    flat
                    round
                    dense
                    color="primary"
                    icon="save"
                    @click="saveItem(props.rowIndex)">
                    <q-tooltip>保存</q-tooltip>
                  </q-btn>
                  <q-btn
                    flat
                    round
                    dense
                    color="negative"
                    icon="mdi-delete-empty"
                    @click="deleteDlgItem(props.rowIndex)">
                    <q-tooltip>删除</q-tooltip>
                  </q-btn>
                </q-td>
              </template>
              <!--   底部插槽     -->
              <template v-slot:bottom>
                <AmyPagination :page-msg="dbPagination" @update="refreshTableAry"/>
              </template>
            </q-table>
          </q-scroll-area>
        </div>
        <div>
          <AmyDeleteDlg
            ref="myDelDlgRef"
            :selected-index="deletedIndex"
            @btnSubmit="submitDelDlg"
          />
        </div>
      </template>
    </q-splitter>
  </div>
</template>

<script lang="ts">
import { defineAsyncComponent, defineComponent, onMounted, onUnmounted, reactive, ref, watch } from 'vue';
import api from 'axios';
import * as XLSX from 'xlsx';
import { useMessageNotify } from 'src/hook/common/useMessageNotify';
import BaseItem from 'pages/BaseItem.vue';
import { ItemType } from 'src/hook/common/useCommonVisitType';
import useCommonVisitDatabase from 'src/hook/common/useCommonVisitDatabase';
import { useCatalogTool } from 'src/hook/common/useCatalogTool';
import { CQueryParam } from 'src/components/basic/basicModel';


import { useHmiCatalogTbl } from '../../../hook/useHmiCatalogTbl';
import { hmiBaseUrlAPI, hmiBaseVOAPI, hmiCatalogType } from '../../../util/HmiBaseConst';
import { useRoute } from 'vue-router';
import { useCommonTree } from 'src/hook/common/useCommonTree';

const AmyDeleteDlg = defineAsyncComponent(() => import('components/basic/AmyDeleteDlg.vue'));
export type DeleteDlgInstance = InstanceType<typeof AmyDeleteDlg>;

export default defineComponent({
  name: 'ComPropsIndex',
  extends: BaseItem,
  components: {

  },
  setup (props, context) {
    //*********************************************************************************************
    //      路由
    //*********************************************************************************************
    //router是全局路由对象，route是当前路由对象
    let curRoute = useRoute();

    //*********************************************************************************************
    //      splitter
    //*********************************************************************************************
    //分割组件分割比例30%
    let splitterRatio = ref(18);

    //*********************************************************************************************
    //      消息通知
    //*********************************************************************************************
    //消息通知
    const {
      showMessage
    } = useMessageNotify();

    //*********************************************************************************************
    //      属性结构管理hook
    //*********************************************************************************************
    //导航树
    const {
      uTreeList,
      getCurrentTree,
      convertToTreeItem
    } = useCommonTree();

    //组件架构树
    let myNavTreeSelectedItem = ref('');
    let myNavTreeRef = ref(null);

    //后台读取数据
    const getCurrentTreeNav = () => {
      getCurrentTree(hmiBaseVOAPI.HMI_COM_TYPE_VO_TREE, null);
    }

    //导航树选择事件
    const onNavTreeSelected = () => {
      if (myNavTreeRef.value) {
        debugger
        let map = convertToTreeItem(myNavTreeSelectedItem.value);
        if (map !== null) {
          queryParam.id = map.sonId;
          queryParam.name = '';

          //新增记录类型修改
          state.itemData.id = map.sonId;

          console.log(map);
          loadList();
        }
      }
    };

    //*********************************************************************************************
    //      查询模块
    //*********************************************************************************************
    //查询输入参数
    let queryParam = reactive({
      id: 0,
      name: '',
      startDate: '',
      endDate: ''
    });


    //有条件查询
    const queryTable = (s: CQueryParam) => {
      let map = convertToTreeItem(myNavTreeSelectedItem.value);
      if (map === null) {
        return;
      }

      //查询条件
      queryParam.name = s.name;
      queryParam.startDate = s.startDate;
      queryParam.endDate = s.endDate;
      queryParam.id = map.parentId;

      //更新
      loadList();
    };


    //*********************************************************************************************
    //      读取表格数据
    //*********************************************************************************************
    //检索响应数据
    const state = reactive({
      itemData: {
        id: 0,
        comId: 0,
        label: '',
        value: '',
        dataTypeId: 0,
        formTypeId: 0,
        optionId: 0,
        sortCode: '',
        description: '',
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      }
    });


    //查询数据库
    const fetchApi = () => {
      return api.post(hmiBaseUrlAPI.HMI_COMPONENT_PROPS_API_PAGE, {
        comId: queryParam.id,
        formTypeId: queryParam.name,
        startDate: queryParam.startDate,
        endDate: queryParam.endDate,
        pageNum: dbPagination.value.pageNum,
        pageSize: dbPagination.value.pageSize
      });
    };

    //删除记录
    const deleteApi = (item: ItemType) => {
      return api.post(hmiBaseUrlAPI.HMI_COMPONENT_PROPS_API_DELETE, { id: item.id });
    };

    //增加记录
    const confirmAddApi = (item: ItemType) => {
      return api.post(hmiBaseUrlAPI.HMI_COMPONENT_PROPS_API_ADD, {
        id: item.id,
        comId: item.comId,
        label: item.label,
        value: item.value,
        dataTypeId: item.dataTypeId,
        formTypeId: item.formTypeId,
        optionId: item.optionId,
        sortCode: item.sortCode,
        description: item.descrption,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };

    //修改记录
    const confirmEditApi = (item: ItemType) => {
      return api.post(hmiBaseUrlAPI.HMI_COMPONENT_PROPS_API_UPDATE, {
        id: item.id,
        comId: item.comId,
        label: item.label,
        value: item.value,
        dataTypeId: item.dataTypeId,
        formTypeId: item.formTypeId,
        optionId: item.optionId,
        sortCode: item.sortCode,
        description: item.descrption,
        createTime: '',
        createUserId: 0,
        updateTime: '',
        updateUserId: 0
      });
    };

    const {
      dbList,
      dbFilterList,
      dbPagination,
      dbCurrentIndex,
      dbStatus,
      getActiveItem,
      getItem,
      filterList,
      loadList,
      addItem,
      editItem,
      deleteItem,
      cancelItem,
      confirmApi
    } = useCommonVisitDatabase(state.itemData, fetchApi, confirmAddApi, confirmEditApi, deleteApi);

    //*********************************************************************************************
    //      目录管理
    //*********************************************************************************************
    const {
      findCatalogLabel,
      findCatalogId
    } = useCatalogTool();

    const {
      propDataTypeList,
      propFormTypeList,
      optionTypeList,
      componentTypeList,
      hmiComponentList,
      getHmiCatalog,
      removeHmiCatalog
    } = useHmiCatalogTbl();


    //*********************************************************************************************
    //      表格
    //*********************************************************************************************
    const columns = [
      {
        name: 'id',
        required: true,
        label: 'ID号',
        align: 'center',
        field: (row:any) => (row.id),
        sortable: true
      },
      { name: 'comId', align: 'center', label: '组件', field: 'comId' },
      { name: 'label', align: 'center', label: '属性标识', field: 'label' },
      { name: 'value', align: 'center', label: '属性值', field: 'value' },
      { name: 'dataTypeId', align: 'center', label: '数据类型', field: 'dataTypeId' },
      { name: 'formTypeId', align: 'center', label: '表单类型', field: 'formTypeId' },
      { name: 'sortCode', align: 'center', label: '序码', field: 'sortCode' },
      { name: 'operation', align: 'center', label: '操作', field: 'operation' }
    ];

    let tableTitle = ref('用户数据');
    let selectedItems = ref([]);
    let filterText = ref('');
    let myDelDlgRef = ref<DeleteDlgInstance|null>(null);
    let deletedIndex = ref(0);
    let bIsReadOnly = ref<boolean[]>([]);

    //检索显示
    const searchTableAry = () => {
      filterList(filterText.value);
    }

    //添加用户
    const addDlgItem = () => {
      addItem();
      filterList(null);
      bIsReadOnly.value.push(true);
      bIsReadOnly.value[0] = false;
    };

    //编辑用户
    const editDlgItem = (row: number) => {
      editItem(row);
      bIsReadOnly.value[row] = false;
    };

    //删除用户
    const deleteDlgItem = (row: number) => {
      if (myDelDlgRef.value) {
        deletedIndex.value = row;
        myDelDlgRef.value.show('组件属性');
      }
    };

    //更新分页组件
    const refreshTableAry = (pageNum: number) => {
      dbPagination.value.pageNum = pageNum;
      loadList();
    };

    //导出excel
    const exportExcel = () => {
      let workbook = XLSX.utils.table_to_book(document.getElementById('my-xls')); //需要在table上定义一个id
      try {
        XLSX.writeFile(workbook, 'BOX信息.xlsx');
      } catch (e) {
        showMessage('导出失败,失败信息:!');
      }
    }

    //保存
    const saveItem = (row: number) => {
      bIsReadOnly.value[row] = true;
      let item = getItem(row);
      if (item !== null) {
        confirmApi(item);
      }
    }

    //状态修改函数
    const refreshReadOnly = () => {
      //清零
      bIsReadOnly.value.length = 0;

      //只读数组
      let size = (dbPagination.value.total >= dbPagination.value.pageSize) ? dbPagination.value.pageSize : dbPagination.value.total;
      for (let i = 0; i < size; i++) {
        bIsReadOnly.value.push(true);
      }
    }

    //*********************************************************************************************
    //      删除确认模块
    //*********************************************************************************************
    //提交确认对话框
    const submitDelDlg = (index: number) => {
      deleteItem(index);
    }

    //*********************************************************************************************
    //      启动模块
    //*********************************************************************************************
    //初始化
    const init = () => {
      //路由信息，修改当前目录树和显示内容
      if (curRoute.query.com_id) {
        let typeId = curRoute.query.typeId as any;
        let comId = parseInt(curRoute.query.com_id as any);
        if (!isNaN(typeId) && !isNaN(comId)) {
          myNavTreeSelectedItem.value = typeId.toString();
          queryParam.id = comId;

          //新增记录类型修改
          state.itemData.comId = comId;
        }
      }

      //树形结构
      getCurrentTreeNav();

      //表格数据,有条件检索
      loadList();

      //读取目录
      getHmiCatalog(hmiCatalogType.PROP_DATA_TYPE_CODE);
      getHmiCatalog(hmiCatalogType.PROP_FORM_TYPE_CODE);
      getHmiCatalog(hmiCatalogType.COMPONENT_TYPE_CODE);
      getHmiCatalog(hmiCatalogType.COMPONENT_CODE);
    }

    //监视检索框
    watch(filterText, () => {
      searchTableAry();
    });

    watch(() => dbPagination, () => {
      refreshReadOnly();
    }, { deep: true });

    //挂载数据
    onMounted(() => {
      init();
    });

    //销毁数据
    onUnmounted(() => {
      removeHmiCatalog(hmiCatalogType.PROP_DATA_TYPE_CODE);
      removeHmiCatalog(hmiCatalogType.PROP_FORM_TYPE_CODE);
      removeHmiCatalog(hmiCatalogType.COMPONENT_TYPE_CODE);
      removeHmiCatalog(hmiCatalogType.COMPONENT_CODE);
    });

    return {
      splitterRatio,

      myNavTreeSelectedItem,
      uTreeList,
      myNavTreeRef,
      getCurrentTreeNav,
      onNavTreeSelected,
      queryTable,

      findCatalogLabel,
      findCatalogId,

      propDataTypeList,
      propFormTypeList,
      optionTypeList,
      componentTypeList,
      hmiComponentList,

      columns,
      tableTitle,
      selectedItems,
      filterText,
      deletedIndex,
      bIsReadOnly,
      myDelDlgRef,

      searchTableAry,
      addDlgItem,
      editDlgItem,
      deleteDlgItem,
      refreshTableAry,
      saveItem,

      dbList,
      dbFilterList,
      dbPagination,
      dbCurrentIndex,
      getActiveItem,

      submitDelDlg,

      exportExcel
    }
  }
})

</script>

<style lang="scss" scoped>
.my_scroll_area_table {
  width: 1000px;
  max-width: 1200px;

  height: 450px;
}
</style>
